package com.budayi.common.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.budayi.common.constants.OssConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author LIBOFEI
 * @ClassName OssClientUtil
 * @description oss工具类
 * @date 2021/4/23 13:38
 * @Version 1.0
 **/
@Component
public class OssClientUtil {


    @Autowired
    private OssConstants ossConstants;

    /** *
     * 上传文件
     * @param  bucketName 上传到的存储桶名称
     * @param  file 要上传的文件
     * @author LIBOFEI
     * @date 13:38 2021/4/23
     * @Version  1.0
    **/
    public  String uploadByFile(String bucketName, File file){
        String after = file.getName().substring(file.getName().lastIndexOf(".") + 1);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String str = dateFormat.format(new Date());
        String name = RandomStrUtil.getRandStr(20);
        String objectName = str + File.separator + name + "." + after;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(ossConstants.getEndpoint(), ossConstants.getAccessKey(), ossConstants.getAccessKeySecret());
        if(!ossClient.doesBucketExist(bucketName)){
            CreateBucketRequest createBucketRequest= new CreateBucketRequest(bucketName);
            createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
            ossClient.createBucket(createBucketRequest);
        }

        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName,objectName, file);
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setObjectAcl(CannedAccessControlList.PublicRead);
        putObjectRequest.setMetadata(metadata);

        // 上传文件。
        ossClient.putObject(putObjectRequest);

        System.out.println(objectName);

        // 关闭OSSClient。
        ossClient.shutdown();
        return objectName;
    }


    public static void main(String[] args) {
        File file = new File("/Users/mac/Pictures/pap.er/f-rticEjF0E.jpg");
        String after = file.getName().substring(file.getName().lastIndexOf(".") + 1);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String str = dateFormat.format(new Date());
        String name = RandomStrUtil.getRandStr(20);
        System.out.println(str + File.separator + name + "." + after);
        System.out.println(file.getName());
        System.out.println(after);
    }
}
